package com.li.jiang.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.li.jiang.mapper.RoleMapper;
import com.li.jiang.mapper.UserRoleMapper;
import com.li.jiang.obj.dto.UserLoginData;
import com.li.jiang.obj.pojo.Role;
import com.li.jiang.obj.pojo.User;
import com.li.jiang.mapper.UserMapper;
import com.li.jiang.obj.pojo.UserRole;
import com.li.jiang.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.li.jiang.utils.redis.RedisUtil;
import com.li.jiang.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 基本用户表 服务实现类
 * </p>
 *
 * @author 李江
 * @since 2024-04-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RedisUtil redisUtil;
    public UserLoginData loginByAccount(String account,String password,Long rid){
//        查询用户
        User u = userMapper.loginByAccount(account,password);
        if (u==null){
            return null;
        }
//        查询用户角色表
        LambdaQueryWrapper<UserRole> queryWrapper
                = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUid,u.getId())
                .eq(UserRole::getRid,rid);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(userRoles)){
            return null;
        }
//       查询角色
        Role role = roleMapper.selectById(rid);

        if (role == null){
            return null;
        }
//        封装用户登录数据
        UserLoginData userLoginData = new UserLoginData();
        userLoginData.setUid(u.getId());
        userLoginData.setAccount(u.getAccount());
        userLoginData.setRid(role.getId());
        userLoginData.setName(u.getName());
        userLoginData.setToken(TokenUtil.createToken());
        userLoginData.setType(role.getRole());
//        创建用户token数据并保存到redis
        String tokenData = TokenUtil.createTokenData(userLoginData);
        redisUtil.set(userLoginData.getToken(),tokenData,RedisUtil.EXPR);

        return userLoginData;
    }

}
